<?php


namespace app\common\model;


use think\Model;

class Order extends Model
{
    /**
     * 获取已经购买的数量
     * @param $user_id
     * @return float|int|string
     */
    public static function getUserBuy($user_id){
        return self::where([
            'user_id'=>$user_id,
            'order_status'=>['not in','10,60'],
            'pay_status'=>20
        ])->count();
    }

    /**
     * 获取个人分享出去的订单数量
     * @param $user_id
     * @return float|int|string
     */
    public static function getUserShareBuy($user_id){
        return self::where([
            'share_id'=>$user_id,
        ])->count();
    }
//    获取唯一核销码
    public static function getTicketCode($buy_mode)
    {
        $str = $buy_mode;
        $str .= randomkeys(6);
//        检查是不是存在，如果不存在就返回
        $isIn = self::where('ticket_code','=',$str)->field('id')->find();
        if (!empty($isIn)){
            self::getTicketCode($buy_mode);
        }else{
            return $str;
        }
    }
//    获取订单编号
    public static function getOrderSn(){
        $str = date('YmdHis').randomkeys(6).session('user.id');
        $isIn = self::where('order_sn','=',$str)->field('id')->find();
        if (!empty($isIn)){
            self::getOrderSn();
        }else{
            return $str;
        }
    }

    public function goods(){
        return $this->belongsTo('goods')->bind(['img_thumb']);
    }
    public function shop(){
        return $this->belongsTo('shop')->bind([
            'shop_img_thumb'=>'img_thumb','shop_name'=>'name'
        ]);
    }
    public function user(){
        return $this->belongsTo('user')->bind([
            'openid','user_nickname'=>'nickname'
        ]);
    }

    public function getOrderStatusTextAttr($value,$data){
        $status = [
            10=>'待支付',
            20=>'已取消',
            30=>'待核销',
            40=>'退款中',
            50=>'已完成',
        ];
        return $status[$data['order_status']];
    }

    public function getPayStatusTextAttr($value,$data){
        $status = [
            10=>'待支付',
            20=>'已支付',
        ];
        return $status[$data['pay_status']];
    }

    public function getBuyModeTextAttr($value,$data){
        $mode = [
            'BUY'=>'正常购买',
            'QIANGGOU'=>'抢购',
            'SHOPBUY'=>'店铺买单',
        ];
        return $mode[$data['buy_mode']];
    }

    public function getExpressTextAttr($value,$data){
        $express = [
            1=>'自取',
            2=>'快递',
        ];
        return $express[$data['express']];
    }
}
